package com.cby.jetpack.sample.binding.custom

import android.graphics.drawable.Drawable
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.BindingAdapter
import androidx.databinding.InverseBindingAdapter
import androidx.databinding.InverseBindingListener
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions

/**
 * @description: CusyomBinding
 *
 * @author ChenBaoyang
 * @date 8/10/21 10:05
 */


object CustomBindingAdapter {

    /**
     * 注解中的属性，就是布局文件中使用的属性， 自定义属性
     * <p>
     *    customText = "111"
     * </p>
     *
     * @param view TextView
     * @param text String
     */
    @JvmStatic
    @BindingAdapter("customText")
    fun setCustomText(view: TextView, text: String) {
        view.text = "$text - customText"
    }

    /**
     * 注解中的属性，就是布局文件中使用的属性， 自定义属性
     * <p>
     *    customText = "111"
     * </p>
     *
     * @param view TextView
     * @param text String
     */
    @JvmStatic
    @BindingAdapter("android:textSize")
    fun setTextSize(view: TextView, fontSize: Float) {
        view.textSize = fontSize+11f
    }

}

/**
 * 自定义绑定属性，加载在线图片
 *
 * @param view ImageView
 * @param imageUrl String
 */
@BindingAdapter(value = ["imageUrl", "placeholder", "error"], requireAll = false)
fun setImageUrl(view: ImageView, imageUrl: String?, placeholder: Drawable, error: Drawable) {
    val options = RequestOptions().also {
        it.centerCrop()
        it.diskCacheStrategy(DiskCacheStrategy.ALL)
        it.placeholder(placeholder)
        it.error(error)
    }
    Glide.with(view.context)
        .load(imageUrl)
        .apply(options)
        .into(view)
}



/**
 * Needs to be used with.
 */
@BindingAdapter("numberOfSets")
fun setNumberOfSets(view: EditText, value: String) {
    view.setText(value)
}

/**
 * Called when the [InverseBindingListener] of the `numberOfSetsAttrChanged` binding adapter
 * is notified of a change.
 */
@InverseBindingAdapter(attribute = "numberOfSets")
fun getNumberOfSets(editText: EditText): String {
    return editText.text.toString()
}


